package com.livestocksolutions.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileFilter;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;

import com.livestocksolutions.LivestockSolutions;

/**
 * Show the progress of the Backup activity to the user.
 * @author Ken DeVries
 * @author Adam Parr
 * 
 * @.modified 25 October 2012
 */
public class BackupFrame extends JFrame {
	private static final long serialVersionUID = 1L;
	private final JProgressBar backupProgress = new JProgressBar();
	private final JButton closeWindow = new JButton("Close");
	private final JLabel backupLabel = new JLabel();
	private boolean running=true;
	private boolean success=false;
	private boolean backup = true;

	/**
	 * Constructor.
	 */
	public BackupFrame(){
		setIconImage(MainFrame.getImage(MainFrame.APP_ICON));
		backupLabel.setHorizontalAlignment(SwingConstants.CENTER);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		add(backupLabel);
		add(backupProgress, BorderLayout.SOUTH);
		setSize(300,100);
		setLocationRelativeTo(null);
		setMinimumSize(new Dimension(300,100));
		backupProgress.setIndeterminate(true);
		backupProgress.setValue(0);
		setVisible(true);
	}
	
	/**
	 * Decide if to backup or restore a backup.
	 * @param backup If <tt>true</tt>, backup, otherwise restore.
	 * @return <tt>true</tt> if backing up, <tt> false</tt> otherwise.
	 */
	public boolean setBackup(boolean backup){
		return this.backup=backup;
	}
	
	/**
	 * Start the Backup/Restore action and display progress and any errors to the user.
	 */
	public void start(){
		running=true;
		String backupPath=LivestockSolutions.getBackupPath();
		setTitle(backup?"Backup":"Restore from Backup");
		backupLabel.setText(backup?"Backing Up...":"Restoring...");
		if(backupPath==null||!backup){
			JFileChooser jfc = new JFileChooser();
			jfc.setAcceptAllFileFilterUsed(false);
			if(backup){
				jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			}else{
				if(backupPath!=null){
					jfc.setCurrentDirectory(new File(backupPath));
				}
				jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
				jfc.setFileFilter(new FileFilter(){
					@Override
					public boolean accept(File pathname) {
						if(pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".zip")){
							return true;
						}
						return false;
					}

					@Override
					public String getDescription() {
						return null;
					}
					
				});
			}
			jfc.setDialogTitle(backup?"Please select where to backup to":"Please select file to restore from");
			if(jfc.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){
				if(backup){
					LivestockSolutions.setBackupPath(jfc.getSelectedFile().getAbsolutePath());
					backupPath=LivestockSolutions.getBackupPath();
				}else{
					backupPath=jfc.getSelectedFile().getAbsolutePath();
				}
			}else{
				dispose();
				return;
			}
		}
		if(backupPath!=null){
			new Thread(){
				@Override
				public void run(){
					while(running){
						try {
							sleep(50);
						} catch (InterruptedException e) {}
						int percent = LivestockSolutions.getProgress();
						percent=percent<0||percent>100?100:percent;
						backupLabel.setText((backup?"Backing Up":"Restoring")+"... ("+percent+"%)");
						backupProgress.setValue(percent);
					}
					setVisible(false);
					String result="";
					if(success){
						result=backup?"Backup Complete<br>Saved to: ":"Restore Successful";
					}else{
						result=(backup?"Backup Failed":"Restore Failed")+"<br>";
					}
					backupLabel.setText("<html><body style=\"text-align:center\">"+result+LivestockSolutions.getMessage()+"</body></html>");

					BackupFrame.this.remove(backupProgress);
					JPanel closePanel = new JPanel();
					closePanel.add(closeWindow, BorderLayout.CENTER);
					add(closePanel, BorderLayout.SOUTH);
					if(backup){
						pack();
					}
					setVisible(true);
					
					closeWindow.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent e){
							interrupt();
							dispose();
						}
					});
				}
			}.start();
			backupProgress.setIndeterminate(false);
			final String pathRestore=backupPath;
			new Thread(){
				@Override
				public void run(){
					success=backup?LivestockSolutions.backup():LivestockSolutions.restore(pathRestore);
					MainFrame.getInstance().refreshTab();
					running = false;
				}
			}.start();
		}
	}
}
